package cn.edu.sctu.sctu_lysd.presenter;

import android.content.Context;
import android.widget.EditText;

import com.google.gson.Gson;

import java.io.IOException;

import cn.edu.sctu.sctu_lysd.bean.ChatToken;
import cn.edu.sctu.sctu_lysd.bean.JsonBaseBeen;
import cn.edu.sctu.sctu_lysd.bean.LoginSuccessData;
import cn.edu.sctu.sctu_lysd.bean.UserProfile;
import cn.edu.sctu.sctu_lysd.biz.LoginBiz;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.net.NetService;
import cn.edu.sctu.sctu_lysd.net.RetrofitHelper;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wangfuxin on 2017-04-06.
 */

public class LoginPresenter implements LoginBiz.Presenter {

    private LoginBiz.View view;
    private Context context;
    private SharePreferenceUtils mSharePreference;
    private NetService service;
    private Call<ResponseBody> registerCall;

    private Call<JsonBaseBeen<UserProfile>> userProfileCall;

    public final static int LOGIN_FAILED_USER_NOT_FOUND = 40000900;
    public final static int LOGIN_FAILED_NET_ERROR = -1;


    public LoginPresenter(LoginBiz.View view, Context context) {
        this.view = view;
        this.context = context;
    }


    @Override
    public void start() {
        mSharePreference = SharePreferenceUtils.getInstance(context);
        RetrofitHelper retrofitHelper = RetrofitHelper.getInstance();
        service = (NetService) retrofitHelper.getService(NetService.class);
    }

    @Override
    public void login(String username, String password) {


        registerCall = service.login(username, password);
        registerCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Gson gson = new Gson();

                    String json = response.body().string();

                    String access_token = json.substring(2, 14);

                    if (access_token.equals("access_token")) {

                        /**
                         * 登陆成功
                         */
                        LoginSuccessData loginSuccessData = gson.fromJson(json, LoginSuccessData.class);

                        L.e("response  getAccess_token", loginSuccessData.getAccess_token());

                        /**
                         * 登陆成功后的逻辑操作
                         */
                        cacheLoginMessage("Bearer " + loginSuccessData.getAccess_token(),
                                loginSuccessData.getRefresh_token());

                        L.e("response  getRefresh_token", loginSuccessData.getRefresh_token());

                        /**
                         * 登陆成功后的UI更新
                         */
                        view.loginSuccess();

                    } else {

                        JsonBaseBeen loginSuccessData = gson.fromJson(json, JsonBaseBeen.class);

                        view.loginFailed(LOGIN_FAILED_USER_NOT_FOUND);

                        L.e("response", loginSuccessData.getMeta().getCode() + "+++++++");

                    }

                } catch (IOException e) {

                    view.loginFailed(LOGIN_FAILED_NET_ERROR);

                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

                t.printStackTrace();
                L.e("response  getMessage", t.getMessage());
                view.loginFailed(LOGIN_FAILED_NET_ERROR);


            }
        });


        /**
         * 登陆操作
         */

    }

    @Override
    public void cacheLoginMessage(String access_token, String refresh_token) {
        mSharePreference.setCache(CacheKeyConfig.CACHE_ACCESS_TOKEN, access_token);
        mSharePreference.setCache(CacheKeyConfig.CACHE_REFRESH_TOKEN, refresh_token);

        /**
         * 获取 user 信息  chatoken 缓存
         */
        getUserProfile();

    }

    @Override
    public void clearEditText(EditText[] view) {

        for (EditText editText : view) {
            editText.setText("");
        }

    }

    @Override
    public void cancel() {

        if (registerCall != null)
            registerCall.cancel();

    }

    @Override
    public String getInputSting(EditText view) {
        return view.getText().toString();
    }

    @Override
    public void getChatToken(final long userId) {

        service.getChatToken(userId).enqueue(new Callback<JsonBaseBeen<ChatToken>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<ChatToken>> call, Response<JsonBaseBeen<ChatToken>> response) {

                if (response.code() == 200 && response.body().getMeta().getCode() == 200){
                    SharePreferenceUtils.getInstance(context).setCache(CacheKeyConfig.CACHE_CHAT_TOKEN,response.body().getData().getToken());

                    view.connectRongyun(response.body().getData().getToken());

                }
            }

            @Override
            public void onFailure(Call<JsonBaseBeen<ChatToken>> call, Throwable t) {

            }
        });

    }

    @Override
    public void getUserProfile() {


        userProfileCall = service.getUserProfile(mSharePreference.getString(CacheKeyConfig.CACHE_ACCESS_TOKEN));

        userProfileCall.enqueue(new Callback<JsonBaseBeen<UserProfile>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<UserProfile>> call, Response<JsonBaseBeen<UserProfile>> response) {

                if (response.body().getMeta().getCode() == 200) {

                    UserProfile data = response.body().getData();


                    mSharePreference.setCache(CacheKeyConfig.CACHE_USER_LOGIN, data.getLogin());
                    mSharePreference.setCache(CacheKeyConfig.CACHE_USER_AVATAR_URL, data.getAvatarUrl());
                    mSharePreference.setCache(CacheKeyConfig.CACHE_USER_NICKNAME, data.getNickname());
                    mSharePreference.setCache(CacheKeyConfig.CACHE_IS_DEPOSIT,data.getDeposit());
                    mSharePreference.setCache(CacheKeyConfig.CACHE_USER_ID,data.getId());

                    L.e("getAvatarUrl", data.getAvatarUrl());

                    getChatToken(data.getId());

                } else {


                }
            }

            @Override
            public void onFailure(Call<JsonBaseBeen<UserProfile>> call, Throwable t) {
            }
        });

    }


}
